<?php

class User_model extends CI_Model {

    public $id;
    public $username;
    public $email;
    public $password;
    public $level;
    public $register_time;
    public $register_ip;
    public $login_time;
    public $login_ip;
    public $status;
    public $department_id;
    public $photo;

    /* 所有用户信息 */

    public function userInfo() {
        $query = $this->db->select('*')->get('su_user');
        return $query->result_array();
    }

    /* 用户登录 */

    public function userLogin($data) {
        $where = [
            'username' => $data['username'],
            'password' => $data['password'],
            'is_verify' => 1
        ];
        $query = $this->db->select('*')->where($where)->get('su_user');
        $info = $query->row_array();
        if ($info) {
            $update = [
                'login_time' => $data['login_time'],
                'login_ip' => $data['login_ip']
            ];
            $this->db->where('username', $data['username'])->update('su_user', $update);
            return $this->db->affected_rows() ? $info : false;
        } else {
            return false;
        }
    }

    /* 用户注册 */

    public function userRegister($data) {
        $state = false;
        $query = $this->db->insert('su_user', $data);
        
        if ($this->db->affected_rows()) {
            if ($data['department_id'] == 0) {
                $department_id = $this->db->insert_id();
                $update = [
                   'department_id' => $department_id
                ];
                $this->db->where("id=$department_id")->update('su_user', $update);
                return $this->db->affected_rows() ? $state=true : $state=false;
            } else {
                $state = true;
            }
        } 
        return $state;
    }

    /* 用户存在 */

    public function userIsExist($username, $email) {
        $where = [
            'username' => $username,
            'email' => $email
        ];
        $query = $this->db->select('id')->or_where($where)->get('su_user');
        return $query->result() ? true : false;
    }
    
    public function updateUserInfo($table,$where,$data){
        $this->db->where($where)->update($table,$data);
        return $this->db->affected_rows()?true:false;
    }

}
